package controller;

import dao.LoginDao;
import utils.Book;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        LoginDao loginDao = new LoginDao();
        System.out.println("name:"+username+"\tpass:"+password);
        int type=loginDao.check(username, password);
        if(type==1){
            req.getSession().setAttribute("user",username);
            Book book = (Book)req.getSession().getAttribute("book");
            System.out.println("普通用户...");
            if (book==null||"".equals(book)){
                req.getRequestDispatcher("/showbook").forward(req,resp);
            }else{
                req.getRequestDispatcher("/order.jsp").forward(req,resp);
            }
        }else if(type==0){
            System.out.println("管理员...");
            req.getRequestDispatcher("/BookServlet?method=search").forward(req,resp);
        }else{
            System.out.println("登录失败...");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
